<?php
/**
 * Created by PhpStorm.
 * User: ytl003
 * Date: 2018/10/1
 * Time: 下午5:23
 */

namespace app\api\service;


use app\api\model\UserModel;
use app\api\validate\WebLoginValidate;
use app\api\validate\WeiAppLoginValidate;
use app\lib\enum\EnumUser;
use app\lib\exception\BaseException;
use app\lib\exception\TokenException;
use think\facade\Request;

class UserService
{
    private function get($code)
    {
        $app = WxService::app()->auth->session($code);
        if (array_key_exists('openid', $app) && $app['openid']) {
            return $app;
        } else {
            throw new BaseException(['msg' => '微信服务器错误请稍后再试！']);
        }
    }

    public function grantToken($type)
    {
        $user = new UserModel();
        $app = null;
        if ($type == 'weiApp') {
            ($validate = new WeiAppLoginValidate())->goCheck();
            $data = $validate->getDataByRule(Request::post());
            $app = $this->get($data['code']);
            $user = $this->weiAppLogin($user, $app);
        }elseif ($type == 'web') {
            ($validate = new WebLoginValidate())->goCheck();
            $data = $validate->getDataByRule(Request::post());
            $user = $this->webLogin($user, $data);
        }else{
            throw new TokenException(['msg' => '不好意思！未传入正确的type我不知道你从那里登陆']);
        }

        $cachedValue = $this->prepareCachedValue($app, $user, $type);
        return $this->saveToCache($cachedValue);
    }

    /**
     * /**
     * @param $user UserModel
     * @param $app
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function weiAppLogin($user, $app)
    {
        $user = $user->where('open_id', $app['openid'])->find();
        if (!$user)
            $user = UserModel::create([
                'open_id'=> $app['openid'],
                'status' => EnumUser::USER
            ]);
        return $user;
    }

    /**
     * @param $user UserModel
     * @param $data
     * @return mixed
     * @throws TokenException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function webLogin($user, $data)
    {
        $user = $user->where('phone', $data['userName'])->find();
        if (!$user)
            throw new TokenException(['msg' => '账号错误']);
        if ($user['password'] != getMd5Password($data['password']))
            throw new TokenException(['msg' => '密码错误']);
        return $user;
    }

    private function saveToCache($cachedValue)
    {
        $key = TokenService::generateToken();
        $value = json_encode($cachedValue);
        $expire_in = config('setting.token_expire_in');
        $request = cache($key, $value, $expire_in);
        if (!$request) {
            throw new TokenException([
                'msg' => '服务器异常',
                'errorCode' => 10005
            ]);
        }
        return $key;
    }

    private function prepareCachedValue($app, $user, $type)
    {
        $cachedValue = $app;
        $cachedValue['userId'] = $user['user_id'];
        $cachedValue['scope'] = $user['status'];
        $cachedValue['type'] = $type;
        return $cachedValue;
    }

}